package com.muyi.biling.ui;

import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.parceler.Parcel;
import org.parceler.Parcels;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import com.muyi.biling.MyApp;
import com.muyi.biling.R;
import com.muyi.biling.SharedPreferencesHelper;
import com.muyi.biling.bean.CommodityItem;
import com.muyi.biling.bean.OrderDetail;
import com.muyi.biling.di.DaggerScope;
import com.muyi.biling.di.Injector;
import com.muyi.biling.util.Utils;

/**
 * Created by developer on 18-1-24.
 */

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(OrderEditActivity.class)
@EActivity(R.layout.activity_order_edit)
public class OrderEditActivity extends AppCompatActivity {

    @ViewById(R.id.order_et_custom)
    EditText etCustom;
    @ViewById(R.id.order_et_tip)
    EditText etTip;

    @ViewById(R.id.order_spinner_logistics)
    Spinner spLogistics;
    @ViewById(R.id.order_spinner_seller)
    Spinner spSeller;

    @ViewById(R.id.order_layout_group)
    LinearLayout layoutGroup;

    @ViewById(R.id.order_tv_sum)
    TextView tvSum;
    @ViewById(R.id.order_tv_number)
    TextView tvNumber;
    @ViewById(R.id.order_tv_date)
    TextView tvDate;

    private String[] mLogisticsData = new String[] {
            "客户自提",
            "送货上门",
            "安能物流",
            "百世物流",
            "鸿昌物流",
    };

    private String[] mSellerData = new String[] {
            "张三",
            "李四",
            "王五",
    };

    @Inject
    SharedPreferencesHelper mSharedHelper;

    private ArrayList<CommodityItem> mData;
    private String mCurrentLogistics;
    private String mCurrentSeller;
    private int mSumPrice;
    private String mStrNumber;
    private String mStrDate;
    private ArrayList<EditText> mEditList;

    @AfterInject
    void initDI() {
        Injector.initOrderEditActivityComponent().inject(this);

        Intent intent = getIntent();
        if (intent != null && intent.getExtras() != null) {
            mData = Parcels.unwrap(intent.getParcelableExtra(CommodityItem.CLASS_NAME));
        }
    }

    @AfterViews
    void initView() {

        initDate();

        if (mData != null) {
            addTabRow();
        }

        spLogistics.setAdapter(new MySpinnerAdapter(mLogisticsData));
        spLogistics.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mCurrentLogistics = mLogisticsData[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spSeller.setAdapter(new MySpinnerAdapter(mSellerData));
        spSeller.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mCurrentSeller = mSellerData[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    @Click(R.id.order_btn_commit)
    void toReviewPage() {
        String custom = etCustom.getText().toString().trim();
        if (TextUtils.isEmpty(custom)) {
            Toast.makeText(this, "客户信息不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        for (EditText editText : mEditList) {
            String itemTip = editText.getText().toString().trim();
            CommodityItem commodityItem = mData.get(mEditList.indexOf(editText));
            commodityItem.tip = itemTip;
        }

        String tip = etTip.getText().toString().trim();

        OrderDetail orderDetail = new OrderDetail(mData, custom, mCurrentLogistics, mCurrentSeller, tip, mSumPrice, mStrNumber, mStrDate);

        Intent intent = new Intent(this, OrderReviewActivity_.class);
        intent.putExtra(OrderDetail.CLASS_NAME, Parcels.wrap(orderDetail));
        startActivity(intent);
    }

    @Click(R.id.order_iv_back)
    void toMainPage() {
        finish();
    }

    private void initDate() {

        long curTime = System.currentTimeMillis();
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy:MM:dd", Locale.getDefault());
        SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm", Locale.getDefault());
        String currentDate = formatDate.format(curTime);
        String currentTime = formatTime.format(curTime);
        String[] splitDate = currentDate.split(":");
        String[] splitTime = currentTime.split(":");
        StringBuilder builderNumber = new StringBuilder();
        StringBuilder builderDate = new StringBuilder();

        builderDate
                .append(splitDate[0])
                .append("年")
                .append(splitDate[1])
                .append("月")
                .append(splitDate[2])
                .append("日");

        builderNumber
                .append("NO：")
                .append(splitDate[0])
                .append(splitDate[1])
                .append(splitDate[2])
                .append(splitTime[0])
                .append(splitTime[1]);

        mStrDate = builderDate.toString();
        mStrNumber = builderNumber.toString();

        tvDate.setText(mStrDate);
        tvNumber.setText(mStrNumber);

    }

    private void addTabRow() {
        int margin = Utils.dp2px(1, this);
        int padding = Utils.dp2px(6, this);
        mEditList = new ArrayList<>();

        for (int i = 0; i < mData.size(); i ++) {
            TableRow tableRow = new TableRow(this);
            tableRow.setGravity(Gravity.CENTER);
            tableRow.setBackgroundColor(Color.BLACK);
            CommodityItem commodityItem = mData.get(i);
            mSumPrice += commodityItem.sumPrice;

            for (int j = 0; j < 5; j ++) {
                TextView textView = new TextView(this);
                textView.setTextColor(Color.BLACK);
                textView.setTextSize(17);
                textView.getPaint().setFakeBoldText(true);
                textView.setPadding(padding, padding, padding, padding);
                textView.setGravity(Gravity.CENTER);
                textView.setBackgroundColor(Color.WHITE);

                TableRow.LayoutParams layoutParams = new TableRow.LayoutParams();
                layoutParams.width = 0;
                layoutParams.height = TableRow.LayoutParams.MATCH_PARENT;

                switch (j) {
                    case 0:
                        textView.setText(commodityItem.title);
                        layoutParams.setMargins(margin, margin, 0, 0);
                        layoutParams.weight = 4;
                        tableRow.addView(textView, layoutParams);
                        break;
                    case 1:
                        textView.setText(String.valueOf(commodityItem.count));
                        layoutParams.setMargins(margin, margin, 0, 0);
                        layoutParams.weight = 1;
                        tableRow.addView(textView, layoutParams);
                        break;
                    case 2:
                        textView.setText(String.valueOf(commodityItem.unitPrice));
                        layoutParams.setMargins(margin, margin, 0, 0);
                        layoutParams.weight = 2;
                        tableRow.addView(textView, layoutParams);
                        break;
                    case 3:
                        textView.setText(String.valueOf(commodityItem.sumPrice));
                        layoutParams.setMargins(margin, margin, 0, 0);
                        layoutParams.weight = 2;
                        tableRow.addView(textView, layoutParams);
                        break;
                    case 4:
                        EditText editText = new EditText(this);
                        editText.setBackgroundResource(R.drawable.shape_null);
                        editText.setTextColor(Color.BLACK);
                        editText.setTextSize(17);
                        editText.getPaint().setFakeBoldText(true);
                        editText.setPadding(padding, padding, padding, padding);
                        editText.setGravity(Gravity.CENTER);
                        layoutParams.setMargins(margin, margin, margin, 0);
                        layoutParams.weight = 3;
                        tableRow.addView(editText, layoutParams);
                        mEditList.add(editText);
                        break;
                }

            }

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Utils.dp2px(70, this));

            layoutGroup.addView(tableRow, layoutParams);
        }

        tvSum.setText("合计：" + String.valueOf(mSumPrice) + "元");

    }


    private class MySpinnerAdapter extends BaseAdapter implements SpinnerAdapter {

        private String[] dataList;

        public MySpinnerAdapter(String[] dataList) {
            this.dataList = dataList;
        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            TextView textView = new TextView(OrderEditActivity.this);
            textView.setText(dataList[position]);
            textView.setTextSize(17);
            textView.setTextColor(Color.BLACK);
            textView.setBackgroundResource(R.drawable.shape_edit_order);
            int padding = Utils.dp2px(10, OrderEditActivity.this);
            textView.setPadding(padding, padding, padding, padding);
            return textView;
        }

        @Override
        public int getCount() {
            return dataList.length;
        }

        @Override
        public Object getItem(int position) {
            return dataList[position];
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(OrderEditActivity.this, R.layout.item_spinner, null);
            TextView textView = view.findViewById(R.id.item_spinner_tv);
            textView.setText(dataList[position]);

            return view;
        }
    }

}
